package com.xm.copyonwritearraylist;

import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSProgressEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 事件监听器列表
 * 使用场景：
 *   迭代器基于创建时的数组快照，即使遍历时有新监听器注册也不受影响。
 *   避免 ConcurrentModificationException，适合动态修改监听器的场景。
 */
public class EventDispatcher {
    private final List<EventListener> listeners = new CopyOnWriteArrayList<>();

    // 注册监听器（线程安全）
    public void addListener(EventListener listener) {
        listeners.add(listener);
    }

    // 触发事件（遍历快照，避免并发修改异常）
    public void fireEvent(Event event) {
        for (EventListener listener : listeners) {
            listener.handleEvent(event);
        }
    }

    public static void main(String[] args) {
        EventDispatcher dispatcher = new EventDispatcher();
        dispatcher.addListener(listener -> System.out.println("Listener 1 handled: " + listener));
        dispatcher.addListener(listener -> System.out.println("Listener 2 handled: " + listener));

        // 触发事件时迭代器不会抛出 ConcurrentModificationException
        new Thread(() -> dispatcher.fireEvent(new LSProgressEvent() {
            @Override
            public LSInput getInput() {
                return null;
            }

            @Override
            public int getPosition() {
                return 0;
            }

            @Override
            public int getTotalSize() {
                return 0;
            }

            @Override
            public String getType() {
                return "";
            }

            @Override
            public EventTarget getTarget() {
                return null;
            }

            @Override
            public EventTarget getCurrentTarget() {
                return null;
            }

            @Override
            public short getEventPhase() {
                return 0;
            }

            @Override
            public boolean getBubbles() {
                return false;
            }

            @Override
            public boolean getCancelable() {
                return false;
            }

            @Override
            public long getTimeStamp() {
                return 0;
            }

            @Override
            public void stopPropagation() {

            }

            @Override
            public void preventDefault() {

            }

            @Override
            public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg) {

            }
        })).start();

        // 动态添加监听器（不影响正在进行的迭代）
        new Thread(() -> dispatcher.addListener(event -> System.out.println("New listener handled: " + event))).start();
    }
}